#include "ZQrControl.h"
namespace ZuiLib
{

ZQrControl::ZQrControl()
	:m_needUpdate(true),m_level(QR_LEVEL_M), m_version(0), m_autoExtent(1), m_maskingNo(-1), m_color(MakeColor(0,0,0))
{
	memset(&m_inset, 0, sizeof(m_inset));
}

void ZQrControl::PaintStatusImage(ZRenderer* render)
{
	if (m_needUpdate)
	{
		m_qrEncoder.EncodeData(m_level, m_version, m_autoExtent, m_maskingNo,
			m_sText, m_sText.GetLength());
		m_needUpdate = false;
	}

	RECT rc = m_rcItem;
    InsetRect(&rc, &m_inset);


	int width = (rc.right - rc.left)/ m_qrEncoder.m_nSymbleSize;
	int height = (rc.bottom - rc.top) / m_qrEncoder.m_nSymbleSize;

	for (int i = 0; i < m_qrEncoder.m_nSymbleSize; ++i)
	{
		for (int j = 0; j < m_qrEncoder.m_nSymbleSize; ++j)
		{
			RECT rcTile = { 
				i*width + rc.left, j*height + rc.top,
				(i+1)*width + rc.left, (j+1)*height + rc.top
			};

			if (m_qrEncoder.m_byModuleData[i][j] == 1)
			{
				render->SetDrawColor(m_color);
				render->FillRect(rcTile);
			}
		}
	}
}

void ZQrControl::SetText(const char* pstrText)
{
	m_sText = pstrText;
	m_needUpdate = true;
	Invalidate();
}

void ZQrControl::SetLevel(int level) 
{
	m_level = level; 
	m_needUpdate = true; 
	Invalidate(); 
}

void ZQrControl::SetVersion(int version) 
{
	m_version = version; 
	m_needUpdate = true; 
	Invalidate(); 
}

void ZQrControl::SetAutoExtent(int autoExtent) 
{ 
	m_autoExtent = autoExtent; 
	m_needUpdate = true; 
	Invalidate(); 
}

void ZQrControl::SetMaskingNo(int maskingNo) 
{
	m_maskingNo = maskingNo; 
	m_needUpdate = true; 
	Invalidate(); 
}

void ZQrControl::SetAttribute(const char* pstrName, const char* pstrValue)
{
	if (stricmp(pstrName, "color") == 0)
	{
		m_color = TextToColor(pstrValue);
	}
	else if (stricmp(pstrName, "inset") == 0)
	{
		ParserRect(&m_inset, pstrValue);
	}
	else
		ZControl::SetAttribute(pstrName, pstrValue);
}

}//namespace

